<?php
/**
 * A simple OpenID consumer component.
 * 
 * Requires PHP OpenID library from http://www.openidenabled.com/openid/libraries/php
 * 
 * Copyright: Daniel Hofstetter  (http://cakebaker.42dh.com)
 * License: MIT
 */
		class OpenidComponent extends Object {
		
		var $controller = null;
		
		function startUp($controller) {
			$this->controller = $controller;
			$pathExtra = APP.DS.'vendors'.DS.PATH_SEPARATOR.VENDORS;
			$path = ini_get('include_path');
			$path = $pathExtra . PATH_SEPARATOR . $path;
			ini_set('include_path', $path);
		}
		
		function authenticate($openId, $processUrl, $trustRoot, $extensionArguments = null) {
			$consumer = $this->__getConsumer();
			$authRequest = $consumer->begin($openId);

			if (!$authRequest) {
			    return false;
			}
			
			if ($extensionArguments != null) {
				foreach ($extensionArguments as $extensionArgument) {
					if (count($extensionArgument) == 3)
					{
						$authRequest->addExtensionArg($extensionArgument[0], $extensionArgument[1], $extensionArgument[2]);
					}
				}
			}
			
			$redirectUrl = $authRequest->redirectURL($trustRoot, $processUrl);

			$this->controller->redirect($redirectUrl);
		}
		
		function getResponse() {
			$consumer = $this->__getConsumer();
			$response = $consumer->complete($_GET);
			
			return $response;
		}
		
		function __getConsumer() {
			vendor('Auth'.DS.'OpenID'.DS.'Consumer');
			vendor('Auth'.DS.'OpenID'.DS.'FileStore');
			
			$storePath = TMP."openid";

			if (!file_exists($storePath) && !mkdir($storePath)) {
			    print "Could not create the FileStore directory '$storePath'. Please check the effective permissions.";
			    exit(0);
			}

			$store = new Auth_OpenID_FileStore($storePath);
			$consumer = new Auth_OpenID_Consumer($store);
			
			return $consumer;
		}
	}
?>
